var floorId;

$(document).ready(function () {

	getMenuList();

	// 内容最小高度
	autoResize();

});
// 获取网页尺寸修改事件
$(window).resize(function(){
	autoResize();
});
function autoResize() {
	var wHeight = $(window).height();
	$(".wrapper").css({"height":wHeight});
    
	var wWidth = ($(window).width()-324)*0.9;
	$("#deviceInfoImgBox").css({"width":wWidth});

	$(".listDeviceBoxList").css({"height":wHeight-165});
}

// 获取页面名字
var urlStrNameArr = location.href.split("?")[0].split("/");
var urlStrName = urlStrNameArr[urlStrNameArr.length-1].split(".")[0];

// 获取url楼层信息
var urlStrFloorArr=new QueryString();
var urlStrFloor=urlStrFloorArr["floor"];

if(!urlStrFloor){
	//默认楼层信息
	switch(urlStrName)
	{
		case 'illumination':
		case 'buildingAir':
		case 'buildingPit':
		case 'buildingWater':
			urlStrFloor = 0;
			break;
		case 'smartSecurityVideoVlc':
		case 'videoSurveillance':
		case 'buildingWind':
		case 'smartSecurity':
		case 'smartSecurityOld':
			urlStrFloor = 1;
			break;
		default:
			urlStrFloor = 0;
	}
}

//获取楼层菜单
var floorsData = {
	cc1:{
		beans:[]
	},
	oldBuild:{
		beans:[]
	}
};
function getMenuList(){
	// PostForm("/cwp/front/sh/intebuilding!execute", "uid=building004", "", outputMenuListFn);
	$.getJSON('/cwp/src/json/device_kongtiao.json',function(data){
        outputMenuListFn(data);
    })
}
function outputMenuListFn(result){
	if(result.returnCode == 0){
		// 保存楼层信息
		var cc1Id;
		var oldId;
		result.beans.forEach(function(data){
			if(data.fullAddress == "cc-1"){
				cc1Id = data.buildingId;
			}else if(data.fullAddress == "老园区生产楼"){
				oldId = data.buildingId;
			}
		});
		result.beans.forEach(function(data){
			if(data.buildingType == "3"){
				if(data.parentId == cc1Id){
					floorsData.cc1.beans.push(data);
				}else if (data.parentId == oldId){
					floorsData.oldBuild.beans.push(data);
				}
			}
		});

		$("#left-menu-secondary").load("/cwp/src/module/common/leftMenuDevice.html",initMenuSecondary);

		if(document.getElementsByClassName('t-building').length != 0){
			outputMenuList(floorsData);
		}
	}else{
		tipModal("icon-cross", "获取楼层失败");
	}
}

//输出楼层
function outputMenuList(result){

	// 楼层
	var floorIndex;
	rightFloorArr.forEach(function(e){
		var thisUrlStrNameArr = e.hrefUrl.split("?")[0].split("/");
		var thisUrlStrName = thisUrlStrNameArr[thisUrlStrNameArr.length-1].split(".")[0];
		if(thisUrlStrName == urlStrName){
			floorIndex = Number(e.floor[urlStrFloor]);
		}
	});

	if(isNaN(floorIndex)){
		// 无楼层
		return;
	}

	if(typeof(buildName)!="undefined" && buildName == "oldBuild"){
		// 老园区
		template.helper('mapFormat', function(inp) {
			if(inp == floorIndex+1){
				return "cur animated fadeInUp";
			}
		});
		template.helper('mapImgFormat', function(inp) {
			switch (inp)
			{
				case "2":
					return "../../../assets/img/building/floor-old-1.png";
					break;
				case "3":
				case "4":
				case "5":
					return "../../../assets/img/building/floor-old-2.png";
					break;
				case "6":
					return "../../../assets/img/building/floor-old-5.png";
					break;
				case "7":
					return "../../../assets/img/building/floor-old-6.png";
					break;
				case "8":
					return "../../../assets/img/building/floor-old-7.png";
					break;
				default:
					return "../../../assets/img/building/floor-old-1.png";
			}
		});

		var outHtml = template("mapTmpl", result.oldBuild);

		outHtml += '<div class="floor-image" id="floorDeviceInfo"></div>';
		outHtml += '<div class="floor-image " id="floorDeviceList"><div id="listDeviceBox"><div id="deviceListTitle">设备列表</div><div class="listDeviceBoxList"><ul></ul></div></div></div>';

		$("#floor-list").html(outHtml);
		floorId = floorsData.oldBuild.beans[floorIndex].buildingId;
	}else{
		// 新园区
		template.helper('mapFormat', function(inp) {
			if(inp == floorIndex+1){
				return "cur animated fadeInUp";
			}
		});
		template.helper('mapImgFormat', function(inp) {
			if(inp == 1){
				if(typeof(deviceTypeId)!="undefined" && deviceTypeId == "1003189"){
					return "../../../assets/img/building/floor-water-0.png";
				}
				return "../../../assets/img/building/floor-0.png";
			}else if(inp == 7){
				return "../../../assets/img/building/floor-6.png";
			}else{
				return "../../../assets/img/building/floor-1.png";
			}
		});

		var outHtml = template("mapTmpl", result.cc1);

		outHtml += '<div class="floor-image" id="floorDeviceInfo"></div>';
		outHtml += '<div class="floor-image " id="floorDeviceList"><div id="listDeviceBox"><div id="deviceListTitle">设备列表</div><div class="listDeviceBoxList"><ul></ul></div></div></div>';

		$("#floor-list").html(outHtml);
		floorId = floorsData.cc1.beans[floorIndex].buildingId;
	}
	// 输出设备
	getDevice(floorId);
	//修改设备列表滚动条bug
	$(".listDeviceBoxList").css({"height":$(window).height()-165});
}

// 渲染中部菜单
function initMenuSecondary(){
	//二级菜单
	var menuHtmlDevice=localStorage.getItem("menuHtmlDevice");

	$('#left-menu-secondary .menu-list-secondary').html(menuHtmlDevice);

	// 动画效果
	$("#left-menu-secondary .left-menu-secondary").addClass("cur animated fadeInUp");

	//获取url菜单参数
	var query=new QueryString();
	var menuId=query["menuId"];
	var menuIdArr = menuId.split(".");
	menuId = menuIdArr[1];

	$("#left-menu-secondary a").each(function(){
		//获取左侧菜单参数
		var dataMenuId= $(this).attr("dataMenuId");
		var thisMenuIdLeft = dataMenuId.substring(dataMenuId.length-2)-1;
		if(menuId == thisMenuIdLeft){
			$(this).parents("li").addClass("selected");
			$(this).find('span.deviceLiIcon').addClass('icon-circle-right');
		}
	});

	//菜单栏滚动条
	$('#left-menu-secondary .menu-list-secondary').slimScroll({
		width: 'auto', //可滚动区域宽度
		height: '100%', //可滚动区域高度
		size: '5px' //组件宽度
	});
}
// 渲染右侧菜单
function drawRightMenu (menu,title) {

	var floorHtml='<div class="rightTitle">'+title+'</div>';

	rightFloorArr.forEach(function(e){
		if(e.fatherId == menu){
			//有楼层信息
			if(e.floor.length > 0){

				floorHtml += template("deviceMenuTmpl", e);

				var thisFloorData;
				if(e.buildName == "cc1"){
					thisFloorData = floorsData.cc1.beans;
				}else{
					thisFloorData = floorsData.oldBuild.beans;
				}
				thisFloorData.forEach(function(g){
					g.hrefUrl = e.hrefUrl;
				});

				e.floor.forEach(function(f,indexf){
					var floorData = thisFloorData[f];

					var thisUrlStrNameArr = floorData.hrefUrl.split("?")[0].split("/");
					var thisUrlStrName = thisUrlStrNameArr[thisUrlStrNameArr.length-1].split(".")[0];

					if( urlStrName == thisUrlStrName && urlStrFloor == indexf){
						floorHtml += '<dd class="floorLi floorSele" >';
					}else{
						floorHtml += '<dd class="floorLi">';
					}
					floorHtml += '<a href="javascript:void(0);" hrefUrl="'+floorData.hrefUrl+'" buildId="'+floorData.buildingId+'" buildNum="'+indexf+'" >'+floorData.buildingDesc+'</a></dd>'
				});

				// 无楼层信息
			}else if(e.hrefUrl != ''){

				var titleUrlNameArr = e.hrefUrl.split("?")[0].split("/");
				var titleUrlName = titleUrlNameArr[titleUrlNameArr.length-1].split(".")[0];

				if(urlStrName == titleUrlName){
					floorHtml += '<dl><dt><i class="title noChild floorLi floorSele"';
				}else{
					floorHtml += '<dl><dt><i class="title noChild floorLi"';
				}
				floorHtml += 'hrefUrl="'+e.hrefUrl+'">'+e.titleName+'</i></dt><div class="dd-list"><div class="div-c">';

				// 开发中
			}else{
				floorHtml += '<dl><dt><i class="title"></i></dt><div class="dd-list"><div class="div-c"><div class="developingTip">设备安装调试中...</div>';
			}

			floorHtml += "</div></div></dl>";
		}
	});

	$('#right-menu-secondary .menu-list-secondary').html(floorHtml);
}
// 绑定菜单
// 中间设备列表
$(document).on("click","#left-menu-secondary a",function(){
	var thisUrl = $(this).attr("datahref");
	if(thisUrl != ''){
		window.location.href = thisUrl;
	}else{
		tipModal("icon-cross", "设备安装调试中...");
	}

});

// 右边楼层
$(document).on("click","#right-menu-secondary dt",function(){
	var t_span=$(this).find("span");
	if(t_span.length>0){
		var className=$(this).find("span").attr("class");
		if(className=="icon-circle-left") {
			className="icon-circle-down";
		} else {
			className="icon-circle-left";
		}
		t_span.attr("class",className);
		$(this).next().filter(':not(:animated)').slideToggle("slow");
	}
});

//楼层切换
$(document).on("click","#right-menu-secondary .dd-list a",function(){
	var thisUrl = $(this).attr("hrefurl");
	var thisUrlStrNameArr = thisUrl.split("?")[0].split("/");
	var thisUrlStrName = thisUrlStrNameArr[thisUrlStrNameArr.length-1].split(".")[0];

	// 楼层index
	urlStrFloor = $(this).attr("buildNum");

	$('#deviceToolBox li').removeClass('selected');
	$("#planeViewBtn").addClass('selected');

	if(urlStrName == thisUrlStrName){
		// 清空设备信息
		$("#deviceInfo").find("li").remove();

		floorId = $(this).attr("buildid");
		$('.floorLi').removeClass("floorSele");
		$(this).parent().addClass("floorSele");

		$("#img-title").removeClass("hide");

		//显示对应楼层
		getDevice(floorId);
		$("#floor-list .floor-image").removeClass("cur animated fadeInUp");
		$("#floor"+floorId).addClass("cur animated fadeInUp");
	}else{
		window.location.href = thisUrl+'&floor='+urlStrFloor;
	}
});

//老园区监控切换
$(document).on("click","#right-menu-secondary dt i.floorLi.noChild",function(){
	var thisUrl = $(this).attr("hrefurl");
	window.location.href = thisUrl;
});

// 浮动显示菜单
var dataMenuIdAni;
$(document).on("mouseover","#left-menu-secondary li",function(){
	$('.right-menu-secondary').css({"width":145});
	$(".center_td").css({"width":290});

	$('#left-menu-secondary li').removeClass('selected');
	$(this).addClass("selected");

	var dataMenuId= $(this).find("a").attr("datamenuid");
	var dataTitle= $(this).find("a").text();
	//energy 取消mouseover事件
	if($(this).find('a').attr('datamenuid') =="100213"){
		$("#right-menu-secondary").hide()
		$(this).find('a').attr('datahref','/cwp/src/static/monitorDevices/energy/energy.html?menuId=1.13')
	}else{
		$("#right-menu-secondary").show()
	}
	drawRightMenu(dataMenuId,dataTitle);

	// 动画效果
	if(dataMenuIdAni != dataMenuId){
		$("#right-menu-secondary .menu-list-secondary").addClass("cur animated fadeInUp");
		setTimeout(function(){
			$("#right-menu-secondary .menu-list-secondary").removeClass("cur animated fadeInUp");
		},1000)
	}
	dataMenuIdAni = dataMenuId;
});

$(document).on("mouseleave","div.center_td",function(){
	$('.right-menu-secondary').css({"width":0});
	$(".center_td").css({"width":145});
	// 默认选项
	$('#left-menu-secondary li').removeClass('selected');

	//获取url菜单参数
	var query=new QueryString();
	var menuId=query["menuId"];
	var menuIdArr = menuId.split(".");
	menuId = menuIdArr[1];
	$("#left-menu-secondary a").each(function(){
		//获取左侧菜单参数
		var dataMenuId= $(this).attr("dataMenuId");
		var thisMenuIdLeft = dataMenuId.substring(dataMenuId.length-2)-1;
		if(menuId == thisMenuIdLeft){
			$(this).parents("li").addClass("selected");
		}
	});
});

// 结构视图平面视图切换
$(document).on("click","#planeViewBtn",function(){
	$('#deviceToolBox li').removeClass('selected');
	$(this).addClass('selected');

	$("#img-title").removeClass("hide");

	getDevice(floorId);
	$("#floor-list .floor-image").removeClass("cur animated fadeInUp");
	$("#floor"+floorId).addClass("cur animated fadeInUp");
});
$(document).on("click","#ListViewBtn",function(){
	$('#deviceToolBox li').removeClass('selected');
	$(this).addClass('selected');

	$("#img-title").removeClass("hide");

	$("#floor-list .floor-image").removeClass("cur animated fadeInUp");
	$("#floorDeviceList").addClass("cur animated fadeInUp");

	loadDeviceList();
});

// 加载设备列表
function loadDeviceList(){
	PostForm("/cwp/front/sh/device!execute", "uid=d001_3&pageSize=100&currentPage=1&deviceTypeId="+deviceTypeId, "",function(result){
		if(result.returnCode == 0){
			var outHtml = '';

			var deviceListA = [],
				deviceListB = [],
				deviceListC = [];

			result.beans.forEach(function (val) {
				switch(val.room)
				{
					case "A区":
						deviceListA.push(val);
						break;
					case "B区":
						deviceListB.push(val);
						break;
					case "C区":
						deviceListC.push(val);
						break;
					default:
						break;
				}
			});

			template.helper("deviceState", function(inp) {
				if(inp == 0){
					return "deviceNormal";
				}else if (inp == 1){
					return "deviceAlarm";
				}else{
					return "deviceClose";
				}
			});
			if(deviceListA.length>0){
				outHtml += "<div class='deviceListAreaTitle'>A区</div>";
				outHtml += template("deviceListTmpl", deviceListA);
			}
			if(deviceListB.length>0){
				outHtml += "<div class='deviceListAreaTitle'>B区</div>";
				outHtml += template("deviceListTmpl", deviceListB);
			}
			if(deviceListC.length>0){
				outHtml += "<div class='deviceListAreaTitle'>C区</div>";
				outHtml += template("deviceListTmpl", deviceListC);
			}
			$("#listDeviceBox ul").html(outHtml);

			if(deviceTypeId == '1003185'){
				$("#deviceListTitle").html("设备列表(空调机组)");
			}

			$('#listDeviceBox ul').slimScroll({
				width: "auto",
				height: '100%',
				alwaysVisible: true,
				size: '5px'
			})
		}
	});
}

//调用设备控制接口
function getControlAccessIpg(_deviceId,_deviceCode,_operaType,_value,susFn,errorFn,errorFn2){
	PostForm("/cwp/front/sh/ipg!execute", "uid=ipg009&deviceCode="+_deviceCode+"&operaType="+_operaType+"&value="+_value, "get",
		function(result){
			if(result.returnCode=="0"){
				tipModal("icon-checkmark", "设备状态更改成功");
				susFn();
				PostForm("/cwp/front/sh/device!execute", "uid=d020&deviceId="+_deviceId+"&operaType="+_operaType+"&value="+_value);
			}else{
				tipModal("icon-cross", "设备状态更改失败");
				errorFn();
			}
		},
		function () {
			tipModal("icon-cross", "接口调用失败");
			errorFn2();
		},
		""
	);
}

// 右边菜单数据
var rightFloorArr = [
	{
		fatherId:'100201',
		titleId:'10020101',
		titleName:'CC-1生产楼',
		hrefUrl:'/cwp/src/static/monitorDevices/smartSecurity/smartSecurityVideoVlc.html?menuId=1.0.0',
		buildName:'cc1',
		floor:['0','1','2','3','4','5']
	},
	{
		fatherId:'100201',
		titleId:'10020102',
		titleName:'老园区室外监控',
		hrefUrl:'/cwp/src/static/emergencyScheduling/videoSurveillance/videoSurveillance.html?menuId=1.0.1',
		buildName:'oldBuild',
		floor:[]
	},
	{
		fatherId:'100202',
		titleId:'100202',
		titleName:'CC-1生产楼',
		hrefUrl:'/cwp/src/static/monitorDevices/illumination/illumination.html?menuId=1.1',
		buildName:'cc1',
		floor:['1','2','3','4','5']
	},
	{
		fatherId:'100203',
		titleId:'100203',
		titleName:'CC-1生产楼',
		hrefUrl:'/cwp/src/static/monitorDevices/building/buildingAir.html?menuId=1.2',
		buildName:'cc1',
		floor:['1','2','3','4','5']
	},
	{
		fatherId:'100204',
		titleId:'100204',
		titleName:'CC-1生产楼',
		hrefUrl:'/cwp/src/static/monitorDevices/building/buildingWind.html?menuId=1.3',
		buildName:'cc1',
		floor:['0','1','6']
	},
	{
		fatherId:'100205',
		titleId:'100205',
		titleName:'CC-1生产楼',
		hrefUrl:'/cwp/src/static/monitorDevices/building/buildingPit.html?menuId=1.4',
		buildName:'cc1',
		floor:['0']
	},
	{
		fatherId:'100206',
		titleId:'100206',
		titleName:'CC-1生产楼',
		hrefUrl:'/cwp/src/static/monitorDevices/building/buildingWater.html?menuId=1.5',
		buildName:'cc1',
		floor:['0']
	},
	{
		fatherId:'100207',
		titleId:'10020701',
		titleName:'CC-1生产楼',
		hrefUrl:'/cwp/src/static/monitorDevices/smartSecurity/smartSecurity.html?menuId=1.6',
		buildName:'cc1',
		floor:['0','1','2','3','4','5']
	},
	{
		fatherId:'100207',
		titleId:'10020702',
		titleName:'老园区生产楼',
		hrefUrl:'/cwp/src/static/monitorDevices/smartSecurity/smartSecurityOld.html?menuId=1.6',
		buildName:'oldBuild',
		floor:['1','2','3','4','5','6','7']
	},
	{
		fatherId:'100208',
		titleId:'100208',
		titleName:'CC-1生产楼',
		hrefUrl:'',
		buildName:'cc1',
		floor:[]
	},
	{
		fatherId:'100210',
		titleId:'100210',
		titleName:'CC-1生产楼',
		hrefUrl:'',
		buildName:'cc1',
		floor:[]
	},
	{
		fatherId:'100209',
		titleId:'100209',
		titleName:'CC-1生产楼',
		hrefUrl:'',
		buildName:'cc1',
		floor:[]
	},
	{
		fatherId:'100211',
		titleId:'100211',
		titleName:'CC-1生产楼',
		hrefUrl:'',
		buildName:'cc1',
		floor:[]
	},
	{
		fatherId:'100213',
		titleId:'100213',
		titleName:'淮安能耗',
		hrefUrl:'',
		buildName:'cc1',
		floor:[]
	},
];

// 远程桌面
$(document).on("click","div.status-bar-laptop",function(){
	if($("#floor-list").hasClass('hide')){
		window.location.reload();
	}else{
		$(".status-bar-laptop div.toLaptop,#floor-list,.img-title,.status-bar").addClass("hide");
		$(".status-bar-laptop div.toHome,#laptop-iframe").removeClass("hide");
	}
});


// function getDevice(){
//     //输出所有子设备
//     // PostForm("/cwp/front/sh/device!execute", "uid=d001_3&pageSize=100&currentPage=1&deviceTypeId="+deviceTypeId+"&buildingId="+floorId, "", outputDevice, '');
//     $.get('/cwp/src/json/device/deviceuidd001_3.json',function(data){
//         outputDevice(JSON.parse(data));
//     })
// }


//输出有所子设备
function outputDevice(result){
    if(result.returnCode  == 0){
        var astr = "";
        var imgurl;
        for(var i=0;i<result.beans.length;i++){
            var deviceState = result.beans[i].deviceState;
            if(deviceState == '0'){
                imgurl = "air1_1.png";
            }else if(deviceState == '1'){
                imgurl = "air1_2.png";
            }else{
                imgurl = "air1_3.png";
            }
            astr += "<a class='shipin' datastate='"+deviceState+"' title='"+result.beans[i].devicePositionDescribe+"' data-port='"+result.beans[i].devicePort+"' data-id='"+result.beans[i].deviceId +"' data-ip='"+result.beans[i].controllerip +"'  data-interfaceaddr='"+result.beans[i].interfaceaddr +"' style='left:"+result.beans[i].deviceX+"%;top:"+ result.beans[i].deviceY +"%'><img src='/cwp/src/assets/img/airConditioner/"+ imgurl +"'/> </a>"
        }
        $("#" + mapid).html(astr);
    }else{
        tipModal("icon-cross", "获取设备失败");
    }
}